package com.sq.partner.manager.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;

import com.sq.partner.manager.common.Config;
import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.common.DictCache;
import com.sq.partner.manager.common.Result;
import com.sq.partner.manager.common.exception.AppException;
import com.sq.partner.manager.dao.ICoreDeptDao;
import com.sq.partner.manager.dao.IGatewayAgentInfoMtDao;
import com.sq.partner.manager.dao.IGatewayAgentInfoRelaDao;
import com.sq.partner.manager.dao.IGatewayChannelInfoConfigDao;
import com.sq.partner.manager.dao.INlifeCoreProdDao;
import com.sq.partner.manager.dao.INlifePlanDao;
import com.sq.partner.manager.dao.INlifeProdDao;
import com.sq.partner.manager.dao.ITradPlanGroupDao;
import com.sq.partner.manager.dao.TradSmsTemplateDao;
import com.sq.partner.manager.mybatis.model.CoreDept;
import com.sq.partner.manager.mybatis.model.DictDto;
import com.sq.partner.manager.mybatis.model.GatewayChannelInfo;
import com.sq.partner.manager.mybatis.model.NlifeCoreProd;
import com.sq.partner.manager.mybatis.model.NlifePlan;
import com.sq.partner.manager.mybatis.model.NlifeProd;
import com.sq.partner.manager.mybatis.model.TradAgentInfoRela;
import com.sq.partner.manager.mybatis.model.TradInsuPlanGroup;
import com.sq.partner.manager.mybatis.model.TradPlanGroup;
import com.sq.partner.manager.mybatis.model.TradSmsTemplate;
import com.sq.partner.manager.service.IGatewayChannelInfoConfigService;
import com.sq.partner.manager.service.IGatewayClearCacheManager;
import com.sq.partner.manager.service.INlifePlanCheckService;
import com.sq.partner.manager.service.ITradInsuPlanGroupService;
import com.sq.partner.manager.util.LogUtil;
import com.sq.partner.manager.util.Page;
import com.sq.partner.manager.util.StrUtil;
import com.sq.partner.manager.util.WebServiceUtil;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

@Service
public class NlifePlanCheckServiceImpl implements INlifePlanCheckService {

	private static Logger logger = LogUtil.getLog(NlifePlanCheckServiceImpl.class);
	
	@Resource
	private INlifePlanDao nlifePlanDao;
	
	@Resource
	private INlifeProdDao nlifeProdDao;

	@Resource
	private INlifeCoreProdDao nlifeCoreProdDao;
	
	@Resource
	private ITradInsuPlanGroupService insuPlanGroupService;
	
	@Resource
	ITradPlanGroupDao planGroupDao;
	
	@Resource
	private IGatewayChannelInfoConfigDao channelInfoDao;
	
	@Resource
	ICoreDeptDao deptDao;
	
	@Resource
	private IGatewayAgentInfoRelaDao agentInfoRelaDao;
	
	@Resource
	private IGatewayAgentInfoMtDao agentInfoDao;
	
	@Resource
	private IGatewayChannelInfoConfigService channelInfoConfigService;
	
	@Resource
	private IGatewayClearCacheManager gatewayClearCacheManager;
	
	@Resource
	private TradSmsTemplateDao tradSmsTemplateDao;

	@Resource
	private ICoreDeptDao coreDeptDao;
	
	@Override
	public Page<GatewayChannelInfo> queryChannelInfoPageByCriteria(
			Page<GatewayChannelInfo> page) throws Exception {
		page = channelInfoDao.getListByDept(page);
		
		return page;
	}
	
	@Override
	public Page<Map<String,Object>> queryNlifePlanPageByCriteria(Page<Map<String,Object>> page)
			throws Exception {
		page = nlifePlanDao.queryPageByCriteria(page);
		
		return page;
	}

	@Override
	public Page<Map<String,Object>> queryUnApproveNlifePlanPageByCriteria(Page<Map<String,Object>> page)
			throws Exception {
		page = nlifePlanDao.queryPageByNewCriteria(page);
		
		return page;
	}
	
//	@Override
//	public Result delNlifePlan(NlifePlan nlifePlan) throws Exception {
//		nlifePlan = nlifePlanDao.queryById(nlifePlan.getPlanNo());
//		String status = nlifePlan.getState();
//		if(1 == Integer.parseInt(status)){
//			return Result.error("该方案状态为有效，不能删除");
//		}else{
//			String prodCode = nlifePlan.getProdCode();
//			NlifeProd nlifeProd = nlifeProdDao.queryProdInfoById(prodCode);
//		
//			String agentType = nlifeProd.getAgentType();
//			//1、合作伙伴代理3、个人代理4、总对总代理
//			if("3".equals(agentType)||"4".equals(agentType)){
//				//根据方案号删除方案下面配置的代理信息
//				agentInfoRelaDao.delTradAgentInfoRelaByPlanNo(nlifePlan.getPlanNo());
//			}
//			boolean flag = nlifePlanDao.delById(nlifePlan.getPlanNo());
//			//清除缓存
//			channelInfoConfigService.clearAllCacheByChannelCode(nlifePlan.getPartnerNo());
//		
//			if(flag){
//				//删除方案组关联
//				insuPlanGroupService.deleteTradInsuPlanGroupByInsuPlanNo(nlifePlan.getPlanNo());
//				return Result.success("删除成功");
//			}else{
//				return Result.error("删除失败");
//			}
//		}
//	}
	@Override
	public void toCheckNlifePlan(ModelMap modelMap,String planNo) throws Exception {
		//页面初始化加载字典表数据
		loadDictDataBeforeAddOrEdit(modelMap);
		List<TradSmsTemplate> messageList = tradSmsTemplateDao.queryTrade(Constants.MESSAGETEMPLATE_TYPE);
		List<TradSmsTemplate> cacelList = tradSmsTemplateDao.queryTrade(Constants.CANCELTEMPLATE_TYPE);
		//两位和四位机构代码
		List<CoreDept> provenceDeptList = coreDeptDao.queryProvenceAndNextLevelDept();
		//车辆类型信息
		List<DictDto> carNatureList = DictCache.getDict("VHL_NLIFE_CAR_MANAGER");//使用的字典待确定
		modelMap.put("planNo", planNo);
		modelMap.put("messageList", messageList);
		modelMap.put("cacelList", cacelList);
		modelMap.put("provenceDeptList", provenceDeptList);
		modelMap.put("carNatureList", carNatureList);
	}
	/**
	 * 新增 或 编辑 页面跳转前 往modelMap中存放字典表数据
	 * @param modelMap
	 * @throws Exception
	 */
	private void loadDictDataBeforeAddOrEdit(ModelMap modelMap) throws Exception{
		//新业务来源
		List<DictDto> newBSList  = DictCache.getDict(Constants.DICT_NEW_BUSINESS_SOURCE);
		//旧业务来源
		List<DictDto> oldBSList = DictCache.getDict(Constants.DICT_OLD_BUSINESS_SOURCE);
		//归属渠道
		List<DictDto> belongToChannelList = DictCache.getDict(Constants.DICT_BELONG_TO_CHANNEL);
		//渠道类型
		List<DictDto> channelTypeList = DictCache.getDict(Constants.DICT_CHANNEL_TYPE);
		//页面初始化加载“附件发送类型”列表
		List<DictDto> Accessorylist=DictCache.getDict(Constants.DICT_NLIFE_ACC_TYPE);
		//回执类型
		List<DictDto> receiptTypeLs = DictCache.getDict(Constants.DICT_RECEIPT_TYPE_OPTIONS);
		//发票购方,1,投保人2,被保人3,接口传入
		List<DictDto> payEinvoices = DictCache.getDict(Constants.DICT_PAY_EINVOICE);
		//分期类型
		List <DictDto> paymentTypeLs =DictCache.getDict(Constants.DICT_PAYMENT_TYPE_OPTIONS);
		modelMap.put("receiptTypeLs", receiptTypeLs);
		modelMap.put("Accessorylist",Accessorylist );
		modelMap.put("oldBSList", oldBSList);
		modelMap.put("newBSList", newBSList);
		modelMap.put("payEinvoices", payEinvoices);
		modelMap.put("belongToChannelList", belongToChannelList);
		modelMap.put("channelTypeList", channelTypeList);
		modelMap.put("paymentTypeLs", paymentTypeLs);
		}

	@Override
	public Map<String, Object> loadNlifePlan(String planNo) throws Exception {
		Map<String,Object> map = new HashMap<String, Object>();

		NlifePlan nlifePlan = nlifePlanDao.queryById(planNo);
		NlifeProd nlifeProd = nlifeProdDao.queryProdInfoById(nlifePlan.getProdCode());
		NlifeCoreProd nlifeCoreProd = nlifeCoreProdDao.queryById(nlifeProd.getCoreProdCode());
		String idStr = nlifePlan.getSelAccessory();
		String[] ids=null;
		if(idStr!=null){
			ids=idStr.split(",");
		}
		map.put("ids", ids);
		map.put("nlifePlan", nlifePlan);
		map.put("nlifeProd", nlifeProd);
		map.put("nlifeCoreProd", nlifeCoreProd);
		
		String agentType= nlifeProd.getAgentType();
		//3 个人  4总对总
		if("3".equals(agentType)||"4".equals(agentType)){
			
			List<Map> agentInfoList = agentInfoRelaDao.queryAgentInfoByInsuPlanNo(planNo);
			map.put("agentInfoList", agentInfoList);
		}
		
		return map;
	}

	@Override
	public Page<NlifeProd> queryNlifeProdPageByCriteria(Page<NlifeProd> page)
			throws Exception {
		page = nlifeProdDao.queryPageByCriteria(page);
		return page;
	}

	@Override
	public Page<CoreDept> queryDeptPageByCriteria(Page<CoreDept> page)
			throws Exception {
		String partnerNo = page.getObj()==null?"":page.getObj().toString();
		page = deptDao.queryCoreDeptPage(page,partnerNo);
		return page;
	}

	@Override
	public List<DictDto> loadSubCascadeList(DictDto dict)
			throws Exception {
		String codeType = dict.getCodeType();
		String parentCode = dict.getParentCode();
		
		List<DictDto> list = new ArrayList<DictDto>();
		if (StrUtil.isNotEmpty(codeType) && StrUtil.isNotEmpty(parentCode)) {
			List<DictDto> subDataList = DictCache.getDictDataByParentCode(codeType, parentCode);
			//复制list
			list.addAll(subDataList);
			//倒序
			Collections.reverse(list);
			DictDto dd = new DictDto();
			dd.setCode("");
			dd.setCodeName("----请选择----");
			list.add(dd);
			//倒序
			Collections.reverse(list);
			return list;
		}else{
			DictDto dd = new DictDto();
			dd.setCode("");
			if(Constants.DICT_CHANNEL_TYPE.equals(codeType)){
				dd.setCodeName("----请选择归属渠道----");
			}else if(Constants.DICT_NEW_BUSINESS_SOURCE.equals(codeType)){
				dd.setCodeName("----请选择渠道类型----");
			}
			list.add(dd);
		}
		return list;
	}

	@Override
	public Result querySauserAndTeamInfo(String COMCODE)
			throws Exception {
		String url = Config.getProp("SALES_WEBSERVICE_URL");
		String method = Config.getProp("querySauserAndTeamInfo_METHOD");
		String namespace = Config.getProp("querySauserAndTeamInfo_NAMESPACE");
		
		//拼接请求报文
		String reqXml = 
				"<?xml version=\"1.0\" encoding=\"GBK\"?>" +
					"<XML>" +
						"<USER>" +
							//归属机构代码(必传)
							"<COMCODE>" + COMCODE + "</COMCODE>" +
							//业务员名称
							"<USERNAME></USERNAME>" +
							//业务员代码(校验使用)
							"<USERCODE></USERCODE>" +
							//渠道名称
							"<CHANNELNAME></CHANNELNAME>" +
							//中介代码
							"<AGENTCODE></AGENTCODE>" +
						"</USER>" +
					"</XML>";
		logger.info("查询业务员-团队信息--》请求报文:"+reqXml);
		
		String respXml = "";
		try{
		    //调用销管接口
			respXml = WebServiceUtil.call(reqXml, url, method, namespace);
			logger.info("查询业务员-团队信息--》返回报文:"+respXml);
		}catch(Exception e){
			logger.info("调用销管接口获取数据异常:",e);
			throw new AppException("调用销管接口获取数据异常:" , e);
		}
		
		// 解析响应报文
		Document document=null;
		try {
			document = DocumentHelper.parseText(respXml);
		} catch (DocumentException e) {
			logger.info("解析销管返回报文异常",e);
			throw new AppException("解析销管返回报文异常:" , e);
		}
		Element root  = document.getRootElement();
		Element RETURN = root.element("RETURN");
		String RETURNCODE = RETURN.elementTextTrim("RETURNCODE");
		Element RETURNMSG = RETURN.element("RETURNMSG");
		
		//存放业务员和团队信息的List
		List<Map<String,Object>> TEAMUSERList = new ArrayList<Map<String,Object>>();
		if("0000".equals(RETURNCODE)){//成功
			List<Element> TEAMUSER_elementList = RETURNMSG.elements("TEAM-USER");
			for (Element TEAMUSER_element : TEAMUSER_elementList) {
				String USERCODE = TEAMUSER_element.elementTextTrim("USERCODE");
				String USERNAME = TEAMUSER_element.elementTextTrim("USERNAME");
				String PHONENO = TEAMUSER_element.elementTextTrim("PHONENO");
				
				Map<String,Object> TEAMUSER = new HashMap<String, Object>();
				TEAMUSER.put("USERCODE", USERCODE);//业务员代码
				TEAMUSER.put("USERNAME", USERNAME);//业务员名称
				TEAMUSER.put("PHONENO", PHONENO);//电话
				
				List<Element> TEAM_elementList = TEAMUSER_element.elements("TEAM");
				//存放每个业务员对应团队信息的List
				List<Map<String,String>> TEAMList = new ArrayList<Map<String,String>>();
				for (Element TEAM_element : TEAM_elementList) {
					String TEAMCODE = TEAM_element.elementTextTrim("TEAMCODE");
					String TEAMNAME = TEAM_element.elementTextTrim("TEAMNAME");
					
					Map<String,String> TEAM = new HashMap<String, String>();
					TEAM.put("TEAMCODE",TEAMCODE);//团队代码
					TEAM.put("TEAMNAME", TEAMNAME);//团队名称
					
					TEAMList.add(TEAM);
				}
				TEAMUSER.put("TEAMList", TEAMList);
				TEAMUSERList.add(TEAMUSER);
			}
		
		}else{
			throw new AppException("调用销管接口获取数据失败:RETURNCODE:" + RETURNCODE +
					"，RETURNMSG:" + RETURNMSG.getTextTrim());
		} 
		return Result.success(TEAMUSERList);
	}

	@Override
	public Result queryAgentAndAgreeInfo(String COMCODE, String TEAMCODE,
			String BUSINESSSOURCE, String CHANNELNAME, String PRODCODE)
			throws Exception {
		String url = Config.getProp("SALES_WEBSERVICE_URL");
		String method = Config.getProp("queryAgentAndAgreeInfo_METHOD");
		String namespace = Config.getProp("queryAgentAndAgreeInfo_NAMESPACE");
		
		//拼接请求报文
		String reqXml = 
				"<?xml version=\"1.0\" encoding=\"GBK\"?>" +
					"<XML>" +
						"<AGENT>" +
							//归属机构代码(必传)
							"<COMCODE>"+ COMCODE +"</COMCODE>" +
							//团队代码(必传)
							"<TEAMCODE>"+ TEAMCODE +"</TEAMCODE >" +
							//业务来源(必传)
							"<BUSINESSSOURCE>"+ BUSINESSSOURCE +"</BUSINESSSOURCE>" +
							//渠道名称(必传)
							"<CHANNELNAME>"+ CHANNELNAME +"</CHANNELNAME>" +
							//产品代码(必传)
							"<PRODCODE>"+ PRODCODE +"</PRODCODE>" +
							//中介代码(校验使用)
							"<AGENTCODE></AGENTCODE>" +
							//业务员名称
							"<USERCODE></USERCODE>" +
						"</AGENT>" +
					"</XML>";
		logger.info("查询中介-协议信息--》请求报文:"+reqXml);
		
		String respXml = "";
		try{
		    //调用销管接口
			respXml = WebServiceUtil.call(reqXml, url, method, namespace);
			logger.info("查询中介-协议信息--》返回报文:"+respXml);
		}catch(Exception e){
			logger.info("调用销管接口获取数据异常",e);
			throw new AppException("调用销管接口获取数据异常:" , e);
		}
		
		// 解析响应报文
		Document document=null;
		try {
			document = DocumentHelper.parseText(respXml);
		} catch (DocumentException e) {
			logger.info("解析销管返回报文异常",e);
			throw new AppException("解析销管返回报文异常:" , e);
		}
		Element root  = document.getRootElement();
		Element RETURN = root.element("RETURN");
		String RETURNCODE = RETURN.elementTextTrim("RETURNCODE");
		Element RETURNMSG = RETURN.element("RETURNMSG");
		
		//存放代理、协议信息的List
		List<Map<String,Object>> AGENTAGREEMENTList = new ArrayList<Map<String,Object>>();
		if("0000".equals(RETURNCODE)){//成功
			List<Element> AGENTAGREEMENT_elementList = RETURNMSG.elements("AGENT-AGREEMENT");
			for (Element AGENTAGREEMENT_element : AGENTAGREEMENT_elementList) {
				String AGENTCODE = AGENTAGREEMENT_element.elementTextTrim("AGENTCODE");
				String AGREEMENTNO = AGENTAGREEMENT_element.elementTextTrim("AGREEMENTNO");
				
				//请求时只有一个PRODCODE值，RISKDETAIL节点则只有一个
				List<Element> RISKDETAIL_elementList = AGENTAGREEMENT_element.elements("RISKDETAIL");
				Element RISKDETAIL_element = RISKDETAIL_elementList.get(0);
				String FEEMAXRATE  = RISKDETAIL_element.elementTextTrim("FEEMAXRATE");
				String FEEMINRATE  = RISKDETAIL_element.elementTextTrim("FEEMINRATE");
				
				double feeMaxRate = 0;
				try{
					feeMaxRate = Double.parseDouble(FEEMAXRATE) * 0.01;
				}catch(Exception e){
					feeMaxRate = 1;
					logger.info(e);
				}
				FEEMAXRATE = Double.toString(feeMaxRate);
				
				double feeMinRate = 0;
				try{
					feeMinRate = Double.parseDouble(FEEMINRATE) * 0.01;
				}catch(Exception e){
					feeMinRate = 0;
					logger.info(e);
				}
				FEEMINRATE = Double.toString(feeMinRate);
				
				Map<String,Object> AGENTAGREEMENT = new HashMap<String, Object>();
				AGENTAGREEMENT.put("AGENTCODE", AGENTCODE);//代理人代码
				AGENTAGREEMENT.put("AGREEMENTNO", AGREEMENTNO);//协议代码
				AGENTAGREEMENT.put("FEEMAXRATE", FEEMAXRATE);//手续费比例上限
				AGENTAGREEMENT.put("FEEMINRATE", FEEMINRATE);//手续费比例下限
				
				AGENTAGREEMENTList.add(AGENTAGREEMENT);
			}
		}else{
			throw new AppException("调用销管接口获取数据失败:RETURNCODE:" + RETURNCODE +
					"，RETURNMSG:" + RETURNMSG.getTextTrim());
		} 
		return Result.success(AGENTAGREEMENTList);
	}

	@Override
	public Result queryServiceNo(String COMCODE, String BUSINESSSOURCE,
			String CHANNELNAME, String USERCODE, String AGENTCODE)
			throws Exception {
		String url = Config.getProp("SALES_WEBSERVICE_URL");
		String method = Config.getProp("queryServiceNo_METHOD");
		String namespace = Config.getProp("queryServiceNo_NAMESPACE");
		
		//拼接请求报文
		String reqXml = 
				"<?xml version=\"1.0\" encoding=\"GBK\"?>" +
						"<XML>" +
							"<AGENT>" +
								//归属机构代码(必传)
								"<COMCODE>"+ COMCODE +"</COMCODE>" +
								//业务来源(必传)
								"<BUSINESSSOURCE>"+ BUSINESSSOURCE +"</BUSINESSSOURCE>" +
								//渠道名称(必传)
								"<CHANNELNAME>"+ CHANNELNAME +"</CHANNELNAME>" +
								//业务员代码(必传)
								"<USERCODE>"+ USERCODE +"</USERCODE>" +
								//中介代码(必传)
								"<AGENTCODE>"+ AGENTCODE +"</AGENTCODE >" +
								//服务代码
								"<SERVICENO></SERVICENO>" +
								//合作机构名称
								"<SERVICENAME></SERVICENAME>" +
							"</AGENT>" +
						"</XML>";
		logger.info("查询服务代码信息--》请求报文:"+reqXml);
		
		String respXml = "";
		try{
		    //调用销管接口
			respXml = WebServiceUtil.call(reqXml, url, method, namespace);
			logger.info("查询服务代码信息--》返回报文:"+respXml);
		}catch(Exception e){
			logger.info("调用销管接口获取数据异常",e);
			throw new AppException("调用销管接口获取数据异常:" , e);
		}
		
		// 解析响应报文
		Document document=null;
		try {
			document = DocumentHelper.parseText(respXml);
		} catch (DocumentException e) {
			logger.info("解析销管返回报文异常",e);
			throw new AppException("解析销管返回报文异常:" , e);
		}
		Element root  = document.getRootElement();
		Element RETURN = root.element("RETURN");
		String RETURNCODE = RETURN.elementTextTrim("RETURNCODE");
		Element RETURNMSG = RETURN.element("RETURNMSG");
		
		//存放服务代码的List
		List<Map<String,Object>> SERVICENOSList = new ArrayList<Map<String,Object>>();
		if("0000".equals(RETURNCODE)){//成功
			List<Element> SERVICENOS_elementList = RETURNMSG.elements("SERVICENOS");
			for (Element SERVICENOS_element : SERVICENOS_elementList) {
				String SERVICENO = SERVICENOS_element.elementTextTrim("SERVICENO");
				String SERVICENAME = SERVICENOS_element.elementTextTrim("SERVICENAME");
				
				Map<String,Object> SERVICENOS = new HashMap<String, Object>();
				SERVICENOS.put("SERVICENO", SERVICENO);//服务代码
				SERVICENOS.put("SERVICENAME", SERVICENAME);//服务名称
				
				SERVICENOSList.add(SERVICENOS);
			}
		}else{
			throw new AppException("调用销管接口获取数据失败:RETURNCODE:" + RETURNCODE +
					"，RETURNMSG:" + RETURNMSG.getTextTrim());
		} 
		return Result.success(SERVICENOSList);
	}
	@Override
	public Result checkNlifePlan(NlifePlan nlifePlan,NlifeProd nlifeProd)  throws Exception {
		//产品销售类型为代理类型
		String planNo = nlifePlan.getPlanNo();
		String state = nlifePlan.getState();
		
		boolean flag = nlifePlanDao.updateForCheck(nlifePlan);
		//清除缓存
		//gatewayClearCacheManager.clearNlifeCacheInfoManager();
//		channelInfoConfigService.clearAllCacheByChannelCode(nlifePlan.getPartnerNo());
		
		if(flag){
			logger.info("==========================审核意见保存成功=============================");
		return Result.success("修改成功");
	}else{
		return Result.error("修改失败");
	}
	}
	
	@Override
	public Page<Map<String, Object>> queryAgentInfoRelaPageByCriteria(
			Page<Map<String, Object>> page, String agentType) throws Exception {
		
		if(agentType.equals("3")){
			page = agentInfoRelaDao.queryAgentInfoRelaWithUserPageByCriteria(page);
		}else if(agentType.equals("4")){
			page = agentInfoRelaDao.queryAgentInfoRelaWithChannelPageByCriteria(page);
		}
		return page;
	}

	@Override
	public Page<Map<String, Object>> queryAgentInfoPageByCriteria(
			Page<Map<String, Object>> page, String agentType) throws Exception {
		
		if(agentType.equals("3")){
			page = agentInfoDao.queryAgentInfoWithUserPageByCriteria(page);
		}else if(agentType.equals("4")){
			page = agentInfoDao.queryAgentInfoWithChannelPageByCriteria(page);
		}
		return page;
	}

	@Override
	public Result updateAgentInfoRela(Long userid, String planNo,
		String agentInfoListStr) throws Exception {
		//1、合作伙伴代理3、个人代理4、总对总代理
		//创建一个JsonParser
		JsonParser parser = new JsonParser();
		//通过JsonParser对象可以把json格式的字符串解析成一个JsonElement对象
		JsonElement jsonElement = parser.parse(agentInfoListStr);
		//把JsonElement对象转换成JsonArray
		JsonArray jsonArray = null;
		if(jsonElement.isJsonArray()){
			jsonArray = jsonElement.getAsJsonArray();
		}
		
		StringBuilder ids = new StringBuilder();
		String idStr = "";
		for (JsonElement je : jsonArray) {
			if(je.getAsJsonObject().get("id")!=null){
				String id =je.getAsJsonObject().get("id").getAsString();
				ids.append(id);
				ids.append(",");
			}
		}
		if(ids.length() > 0){
			idStr=ids.substring(0, ids.length()-1);
		}
		
		agentInfoRelaDao.delTradAgentInfoRelaByInsuplannoAndAgentIds(planNo, idStr);
		
		boolean flag = false;
		for (JsonElement je : jsonArray) {
			String id ="";
			if(je.getAsJsonObject().get("id")!=null){
				id =je.getAsJsonObject().get("id").getAsString();
			}
			String commRate=je.getAsJsonObject().get("commrate").getAsString();
			if(StrUtil.isNotEmpty(id)){
				TradAgentInfoRela agentInfoRela =new TradAgentInfoRela();
				agentInfoRela.setAgentInfoId(Long.valueOf(id));
				agentInfoRela.setInsuPlanNo(planNo);
				if(StrUtil.isNotEmpty(commRate)){
					BigDecimal bigDecimal = new BigDecimal(commRate);
					bigDecimal = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP); 
					agentInfoRela.setCommRate(bigDecimal);
				}
				agentInfoRela.setOperTime(new Date());
				agentInfoRela.setOperUser(userid);
				flag = agentInfoRelaDao.addOrUpdateTradAgentInfoRela(agentInfoRela);
			}
		}
		
		if(flag){
			return Result.success("更新成功");
		}
		return Result.error("更新失败");
	}

	@Override
	public List<NlifePlan> queryPartnerInfoByProdCode(String prodCode) throws Exception {
		return nlifePlanDao.queryPartnerInfoByProdCode(prodCode);
	}

	
}
